package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.constant.ReportStateConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * author:z
 * time:2021/12/29 17:22
 * description:扣费策略
 */
@Service(value = "fee")
@Slf4j
public class FeeChainManagerImpl implements FilterChainService{
    @Autowired
    CacheFeign cacheFeign;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("[策略模块-扣费策略]开始执行！");
        //1.获取用户账户余额
        Map<String,String> clientMap = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID());
        if(clientMap==null){
            log.info("策略模块-扣费策略]获取用户对象失败,standardSubmit={}",standardSubmit);
            return false;
        }
        long totalFee = Long.parseLong(clientMap.get("fee"));
        //2.获取当前这条短信的费用
        Long fee = standardSubmit.getFee();
        //3.判断账户余额一定要大于当前这条短信的费用
        if(totalFee>=fee){
            //4.完成扣费
            cacheFeign.hincr(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(),"fee",-fee);
            log.info("[策略模块-扣费策略]执行结束！");
            return true;
        }else{
            //5.如果用户费用不足，扣费失败，记录日志，并通知用户扣费失败提醒充值
            //给用户发送状态报告，推送失败的原因数据
            pushMsgUtil.pushReport(standardSubmit,String.valueOf(ReportStateConstants.FAIL));
            //将用户失败数据发送到MQ日志队列中，提供后期查账使用
            pushMsgUtil.sendLog(standardSubmit,String.valueOf(ReportStateConstants.FAIL));
            log.info("[策略模块-扣费策略]扣费失败，用户账户余额不足，请及时充值！standardSubmit={}",standardSubmit);
            return false;
        }
    }
}
